﻿using lcwb.Shared.Api;
using lcwb.Shared.Model;
using System.Net.Http.Json;

namespace lcwb.Shared.Service
{
    public class ArticleService
    {
        private readonly HttpClient _httpClient;
        // Implement comment and Articles
        public ArticleService(IHttpClientFactory httpClientFactory)
        {
            _httpClient = httpClientFactory.CreateClient("ServerApi");
        }

        public async Task<Article> GetArticleByIdAsync(int Id)
        {
            try
            {
                string Api = $"/api/Article/{Id}";
                var response = await _httpClient.GetAsync(Api);
                if (response.IsSuccessStatusCode)
                {
                    ApiResponse<Article>? res = await response.Content.ReadFromJsonAsync<ApiResponse<Article>>();
                    if (res != null)
                    {
                        return res.Data ?? new Article();
                    }
                    else
                    {
                        return new Article();
                    }
                }
                else
                {
                    Console.Error.WriteLine($"API request failed with status code: {response.StatusCode}");
                    return new Article();
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine($"An error occurred while fetching courses: {ex.Message}");
                return new Article();
            }
        }
    }
}
